/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.worldscale.xp.wslib.im.jabber.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Vector;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

/**
 *
 * @author Kun
 */
public final class My_TCP_TLS_Connection implements MyAbstractConnection {

    public static My_TCP_TLS_Connection open(String host, int port) throws IOException {
        final InetSocketAddress addr = new InetSocketAddress(host, port);
        final Socket sock = new Socket();
        sock.connect(addr);
        return new My_TCP_TLS_Connection(sock);
    }
    private Socket mSock;

    private My_TCP_TLS_Connection(Socket sock) {
        mSock = sock;
    }

    public void close() throws IOException {
        mSock.close();
    }

    public InputStream openInputStream() throws IOException {
        return mSock.getInputStream();
    }

    public OutputStream openOutputStream() throws IOException {
        return mSock.getOutputStream();
    }

    public void startTLS() throws IOException {
        final InetSocketAddress addr = (InetSocketAddress) this.mSock.getRemoteSocketAddress();
        final String host = addr.getHostName();
        final int port = addr.getPort();
        //
        final SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
        final SSLSocket sslsock = (SSLSocket) f.createSocket(mSock, host, port, true);
        //
        final String[] supports = sslsock.getSupportedCipherSuites();
        final Vector<String> vec = new Vector<String>();
        for (int i = 0; i < supports.length; i++) {
            final String s = supports[i];
            if (s.contains("TLS")) {
                vec.addElement(s);
            }
        }
        final String[] enable = new String[vec.size()];
        vec.copyInto(enable);
        sslsock.setEnabledCipherSuites(enable);
        //
        sslsock.startHandshake();
        this.mSock = sslsock;
    }
}
